package com.ww.springstudy.spel;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述：
 *
 * @author 🧑 ‍wanwei
 * @since 2025-01-20 17:38
 */
public class Demo1 {

     Map<String,String> map = new HashMap(){
        {
           put("name","ww");
        }
    };

    public static void main(String[] args) {
        // 基本表达式
        SpelExpressionParser parser = new SpelExpressionParser();
        EvaluationContext context = new StandardEvaluationContext();

        // 字面量表达式
        String helloWorld = parser.parseExpression("'Hello World'").getValue(String.class);
        System.out.println(helloWorld);
        // 变量访问
        context.setVariable("name", "World");
        String greeting = parser.parseExpression("'Hello' + ' ' + #name").getValue(context, String.class);
        System.out.println(greeting);

        // 方法调用
        Integer length = parser.parseExpression("'Hello World'.length()").getValue(Integer.class);
        System.out.println(length);

        // 类型表达式
        Class<?> stringClass = parser.parseExpression("T(java.lang.String)").getValue(Class.class);
        System.out.println(stringClass.getSimpleName());

        // 集合选择
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
        context.setVariable("numbers", numbers);
        List<Integer> evenNumbers = parser.parseExpression("#numbers.?[#this % 2 == 0]").getValue(context, List.class);
        System.out.println(evenNumbers);



        List<User> users = Arrays.asList(
           new User("ww",0),
           new User("ww2",0),
           new User("ww3",0)
        );
        context.setVariable("users", users);
        // 集合投影
        List<String> names = parser.parseExpression("#users.![name]").getValue(context, List.class);
        System.out.println(names);
        System.out.println(names.size());
        // 集合投影
        names = parser.parseExpression("#users.![name]+ ' ' + #users.![age]").getValue(context, List.class);
        System.out.println(names);
        System.out.println(names.size());
        String sss = parser.parseExpression("#users.![name] + ' ' + #users.![age]").getValue(context, String.class);
        System.out.println(sss);
    }
}
